//
//  ConfirmOrderViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/21.
//  Copyright © 2018年 四川中农. All rights reserved.
//

typealias BackSeleGoods = (NSMutableDictionary)->Void

import UIKit
import HandyJSON

class ConfirmOrderViewController: BaseViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var discountsMoney: UILabel! // 已优惠金额
    @IBOutlet weak var totalMoney: UILabel!
    
    var backSeleGoods:BackSeleGoods!
    
    var seleTimeArray = [String]()// 没个section 显示的送达时间
    
    var timeArray = [String]() // 可选择送达时间的属猪
    
    var dataArray = [[SiteGoodsModel]]()
    
    var goodsArray = [Any]()
    
    var type = 0 // 订单类型 0立即支付 1货到付款
    
    var couponId = 0 // 优惠卷id
    
    var remarks = ""
    
    var seleGoodsIndexArray = NSMutableArray()  // 选中商品的id
    
    var seleGoodsDic = NSMutableDictionary() // key：商品id  value：选中商品的数量
    
    var seleGoodsIndexSecton = 0
    
    var couponCount = 0
    
    var allMonry:Double = 0
    
    var biaoLeiMoney:Double = 0
    
    var couponMoney:Double = 0
    
    var isHaveBiaoLei = false
    
    var biaoLeiTime = ""
    
    lazy var pickerView:SeleTimePickerView = {
        var picker = SeleTimePickerView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(picker)
        picker.backSeletime = { [weak self] (time) in
            self?.changeServiceTime(time: time)
        }
        return picker
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "确认订单"
        self.tableView.separatorStyle = .none
        
        var array0 = [SiteGoodsModel]()
        var array1 = [SiteGoodsModel]()
        var array2 = [SiteGoodsModel]()
        
        self.tableView.backgroundColor = UIColor.backgroundColor
    
        for model in self.seleGoodsIndexArray {
            let obj = model as! SiteGoodsModel
            if obj.packageId == 0 {
                array0.append(obj)
                
            }else if obj.packageId == 1 {
                array1.append(obj)
            }else{
                array2.append(obj)
            }
        }
        
        if array0.count != 0 {
            self.isHaveBiaoLei = true
            self.dataArray.append(array0)
            self.seleTimeArray.append("")
        }
        if array1.count != 0 {
            self.dataArray.append(array1)
            self.seleTimeArray.append("请选择计划送达时间")
        }
        if array2.count != 0 {
            self.dataArray.append(array2)
            self.seleTimeArray.append("请选择计划送达时间")
        }
        
        getCouponCount()
        checkGoodsDic()
    }
    
    func checkGoodsDic(){
        DispatchQueue.global().async {
            
            var totalPrice:Double = 0
            for array in self.dataArray{
                var goodsDic = [String:Any]()
                var price:Double = 0
                var arr = [[String:Int]]()
                var type = 0
                for model in array {
                    let count = self.seleGoodsDic.object(forKey: "\(model.id)") as! Int
                    var currentPrice:Double = 0
                    type = model.packageId
                    if model.isDiscount == 1 {
                        currentPrice = model.discountMoney
                    }else if model.isActivity == 1 {
                        currentPrice = model.activityMoney
                    }else if model.peddlersPrice != nil {
                        currentPrice = Double.init((model.peddlersPrice)!)!
                    }else{
                        currentPrice = model.price
                    }
                    price = price + Double(count) * currentPrice
                    
                    arr.append(["goodsId":model.id,"num":count])
                    if model.packageId == 0 {
                        self.biaoLeiMoney = self.biaoLeiMoney + Double(count) * currentPrice
                    }
                }
                goodsDic["list"] = arr
                goodsDic["money"] = price
                if type == 0 {
                    goodsDic["serviceTime"] = "次日上午十一点半"
                }else{
                    goodsDic["serviceTime"] = ""
                }
                goodsDic["type"] = type
                self.goodsArray.append(goodsDic)
                totalPrice = totalPrice + price
            }
            self.allMonry = totalPrice
            Utils.dispatchMainQueue {
                self.updateTotalMoney()
            }
        }
    }
    
    func updateTotalMoney(){
        var attribute = NSMutableAttributedString.init(string: "合计：￥" + "\(self.allMonry - self.couponMoney)")
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], range: NSString.init(string: "合计：￥" + "\(self.allMonry)").range(of: "￥" + "\(self.allMonry - self.couponMoney)"))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 17)], range: NSString.init(string: "合计：￥" + "\(self.allMonry)").range(of: "\(self.allMonry - self.couponMoney)".getPriceInteger()))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: "合计：￥" + "\(self.allMonry)").range(of: "￥" + "\(self.allMonry - self.couponMoney)"))
        self.totalMoney.attributedText = attribute
    }
    
    func changeServiceTime(time:String){
        var goodsDic = self.goodsArray[self.seleGoodsIndexSecton] as! [String:Any]
        goodsDic["serviceTime"] = time
        self.goodsArray.remove(at: self.seleGoodsIndexSecton)
        self.goodsArray.insert(goodsDic, at: self.seleGoodsIndexSecton)
        
        self.seleTimeArray.remove(at: self.seleGoodsIndexSecton)
        self.seleTimeArray.insert(time, at: self.seleGoodsIndexSecton)
        self.tableView.reloadSections(IndexSet.init(integer: self.seleGoodsIndexSecton + 2), with: UITableViewRowAnimation.fade)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK:提交订单
    @IBAction func submitOrder(_ sender: UIButton) {
        
        PKhud.show()
        
        let parameter:postParameters = ["json":Utils.dataTypeTurnJson(element: self.goodsArray),
                                        "type":self.type,
                                        "userCouponId":self.couponId,
                                        "remarks":self.remarks]
        HttpRequest.requestData(.post, URLString: Api.orderCreate.rawValue, parameters: parameter) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.couponCount = self.couponCount - 1
                if self.couponCount < 0 {
                    self.couponCount = 0
                }
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2+self.dataArray.count)) as? RemarkAndCouponTableViewCell
                cell?.coupon.text = "\(self.couponCount)" + "张可用"
                if self.type == 1 {
                    let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CheckstandViewController") as! CheckstandViewController
                    ctrl.payType = .payOnDelivery
                    ctrl.isBalancePay = false
                    self.navigationController?.pushViewController(ctrl, animated: true)
                }else{
                    if let model = JSONDeserializer<ConfirmOrderModel>.deserializeFrom(dict: result["data"] as? postParameters){
                        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SelePayViewController") as! SelePayViewController
                        ctrl.model = model
                        self.navigationController?.pushViewController(ctrl, animated: true)
                    }
                }
                
                if self.backSeleGoods != nil {
                    self.backSeleGoods(self.seleGoodsDic)
                }
                
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    /// 优惠卷数量
    func getCouponCount(){
        HttpRequest.requestData(.post, URLString: Api.couponList.rawValue, parameters: ["type":0]) { (result) in
            if result["msg"] as! String == "success"{
                let array = result["data"] as? [Any]
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2+self.dataArray.count)) as? RemarkAndCouponTableViewCell
                self.couponCount = (array?.count)!
                cell?.coupon.text = "\(array?.count ?? 0)" + "张可用"
                
                if self.isHaveBiaoLei {
                    // 标类送达时间
                    HttpRequest.requestData(.post, URLString: Api.orderServiceTime.rawValue, parameters: ["type":0]) { (result) in
                        if result["msg"] as! String == "success"{
                            if let array = (result["data"] as? [Any]) as? [String]{
                                self.biaoLeiTime = array.first!
                                
                                for (idx,obj) in self.goodsArray.enumerated() {
                                    var dic:[String:Any] = obj as! [String:Any]
                                    if dic["type"] as! Int == 0 {
                                        dic["serviceTime"] = self.biaoLeiTime
                                    }
                                    self.goodsArray.remove(at: idx)
                                    self.goodsArray.insert(dic, at: idx)
                                    break
                                }
                                
                                for (idx,obj) in self.seleTimeArray.enumerated(){
                                    if obj == "" {
                                        self.seleTimeArray.remove(at: idx)
                                        self.seleTimeArray.insert(self.biaoLeiTime, at: idx)
                                    }
                                }
                                
                                self.tableView.reloadData()
                            }
                        }else{
                            PKhud.showText(text: result["data"] as! String)
                        }
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    
    // MARK:获取订单送达时间
    func getOrderServiceTime(title:String){
        HttpRequest.requestData(.post, URLString: Api.orderServiceTime.rawValue, parameters: ["type":1]) { (result) in
            if result["msg"] as! String == "success"{
                if let array = (result["data"] as? [Any]) as? [String]{
                    self.timeArray = array
                    self.pickerView.reloadAll(titleArray: self.timeArray, andTitle: title)
                    self.pickerView.show()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func backBarButtonMethon() {
        PKhud.hiden()
        self.pickerView.removeFromSuperview()
        self.navigationController?.popViewController(animated: true)
    }

}

extension ConfirmOrderViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 3 + self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 1 || section == 2 + self.dataArray.count {
            return 1
        }else{
            return self.dataArray[section-2].count
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessDetailTableViewCell") as! BusinessDetailTableViewCell
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SelePayTypeTableViewCell") as! SelePayTypeTableViewCell
            if self.type == 0 {
                cell.onLineImageV.isHighlighted = true
                cell.huodaofukuanImageV.isHighlighted = false
            }else{
                cell.onLineImageV.isHighlighted = false
                cell.huodaofukuanImageV.isHighlighted = true
            }
            cell.backPayType = { [weak self] (type) in
                self?.type = type
            }
            return cell
        }
        
        if indexPath.section - 2 < self.dataArray.count {
            let cell = tableView.dequeueReusableCell(withIdentifier: "GoodsIntroduceTableViewCell") as! GoodsIntroduceTableViewCell
            let model = self.dataArray[indexPath.section - 2][indexPath.row]
            cell.reload(withModel: model, count: self.seleGoodsDic.object(forKey: "\(model.id)") as! Int)
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "RemarkAndCouponTableViewCell") as! RemarkAndCouponTableViewCell
            cell.coupon.text = "\(self.couponCount)" + "张可用"
            if self.isHaveBiaoLei == false {
                cell.couponViewHeight.constant = 0
            }
            cell.backRemarkString = { [weak self] (remarks) in
                self?.remarks = remarks
            }
            cell.seleCoupon = { [weak self] in
                if self?.couponCount == 0 {
                    PKhud.showText(text: "没有可用的优惠券吧~")
                    return
                }
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "MyCouponTableViewController") as! MyCouponTableViewController
                ctrl.isSeleCoupon = true
                ctrl.couponID = (self?.couponId)!
                ctrl.money = (self?.biaoLeiMoney)!
                ctrl.seleCoupon = { [weak self] (coupon) in
                    self?.discountsMoney.text = "已优惠¥" + "\(coupon.jian)"
                    self?.couponId = coupon.userCouponId
                    cell.coupon.text = coupon.name
                    self?.couponMoney = Double.init(coupon.jian)
                    self?.updateTotalMoney()
                }
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            self.tableView.estimatedRowHeight = 105
            self.tableView.rowHeight = UITableViewAutomaticDimension
            return self.tableView.estimatedRowHeight
        }
        
        if indexPath.section == 1 {
            return 110
        }
        
        if  indexPath.section - 2 < self.dataArray.count {
            return 100
        }else{
            self.tableView.estimatedRowHeight = 155
            self.tableView.rowHeight = UITableViewAutomaticDimension
            return self.tableView.estimatedRowHeight
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 || section == 1 || section == 2 + self.dataArray.count {
            return 0.01
        }else{
            return 28
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 || section == 1 || section == 2 + self.dataArray.count {
            return 10
        }else{
            return 65
        }
    }
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section > 1 && section != 2 + self.dataArray.count {
            let header = UIView()
            header.backgroundColor = UIColor.white
            header.frame = CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 28)
            let titleLabel = Utils.labelWith(frame: CGRect.init(x: 11.5, y: 28 - 15, width: 80, height: 15), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: NSTextAlignment.left, textColor: "#000000", text: "")
            switch section - 2 {
                case 0:
                    titleLabel.text = "包裹1"
                case 1:
                    titleLabel.text = "包裹2"
                case 2:
                    titleLabel.text = "包裹3"
                default:
                    break
            }
            header.addSubview(titleLabel)
            return header
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section > 1 && section != 2 + self.dataArray.count {
            let footer = UIView()
            footer.frame = CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 65)
            footer.backgroundColor = UIColor.backgroundColor
            let bgView = UIView.init()
            bgView.backgroundColor = UIColor.white
            bgView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 55)
            footer.addSubview(bgView)
            
            let dic = self.goodsArray[section - 2] as! [String:Any]
            let str = "小计：¥" + "\(dic["money"] as! Double)"
            let width = str.rect(withFont: UIFont.systemFont(ofSize: 13), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 15)).width + 20
            let totalPrice = Utils.labelWith(frame: CGRect.init(x: 11.5, y: 0, width: width, height: 15), font: UIFont.systemFont(ofSize: 13), textAlignment: .left, textColor: "#333333", text: "")
            bgView.addSubview(totalPrice)
            
            totalPrice.centerY = bgView.centerY
            
            var attribute = NSMutableAttributedString.init(string: str)
            attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], range: NSString.init(string: str).range(of: "￥" + "\(dic["money"] as! Double)"))
            
            attribute = NSMutableAttributedString.init(attributedString: attribute)
            attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 17)], range: NSString.init(string: str).range(of: "\(dic["money"] as! Double)".getPriceInteger()))
            
            attribute = NSMutableAttributedString.init(attributedString: attribute)
            attribute.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: str).range(of: "¥" + "\(dic["money"] as! Double)"))
            totalPrice.attributedText = attribute
            
            let timeLabel = Utils.labelWith(frame: CGRect.init(x: totalPrice.right + 20, y: 20, width: UIScreen.ScreenWidth - 32 - totalPrice.right, height: 15), font: UIFont.systemFont(ofSize: 15), textAlignment: NSTextAlignment.right, textColor: "#333333", text: "")
            timeLabel.tag = 100 + section
            bgView.addSubview(timeLabel)
            
            let time = self.seleTimeArray[section - 2]
            timeLabel.text = time
            
            let model = self.dataArray[section-2].first!
            if model.packageId == 0 {
                timeLabel.textColor = UIColor.init(hexColor: "#333333")
            }else{
                timeLabel.textColor = UIColor.init(hexColor: "#f7c201")
            }
            
            let labelTap = UITapGestureRecognizer.init(target: self, action: #selector(handleClick(sender:)))
            timeLabel.addGestureRecognizer(labelTap)
            timeLabel.isUserInteractionEnabled = true
            
            return footer
        }
        return UIView()
    }
    
    
    @objc func handleClick(sender:UITapGestureRecognizer){
        let label:UILabel = sender.view as! UILabel
        
        if label.text == self.biaoLeiTime || label.text == "" {
            return
        }
        var title = ""
        self.seleGoodsIndexSecton = label.tag - 100 - 2
        
        switch label.tag - 100 - 2 {
        case 0:
            title = "包裹1送达时间"
        case 1:
            title = "包裹2送达时间"
        case 2:
            title = "包裹3送达时间"
        default:
            break
        }
        
        if self.timeArray.count == 0 {
            self.getOrderServiceTime(title: title)
        }else{
            self.pickerView.reloadAll(titleArray: self.timeArray, andTitle: title)
            self.pickerView.show()
        }
    }
}





















